package studio.mandysa.jiuwo.ktx

import android.annotation.SuppressLint
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.viewinterop.AndroidView
import androidx.recyclerview.widget.RecyclerView
import studio.mandysa.jiuwo.adapter.RecyclerAdapter

@Composable
@SuppressLint("ModifierParameter")
fun Linear(
    headers: List<Any> = arrayListOf(),
    models: List<Any> = arrayListOf(),
    footers: List<Any> = arrayListOf(),
    @RecyclerView.Orientation orientation: Int = RecyclerView.VERTICAL,
    modifier: Modifier = Modifier,
    init: RecyclerView.() -> Unit = {},
    block: RecyclerAdapter.() -> Unit = {}
) {
    RecyclerView(
        modifier = modifier
    ) {
        if (it.adapter == null) {
            init.invoke(it)
            it.linear(orientation).setup {
                block.invoke(this)
            }
        }
        if (it.adapter is RecyclerAdapter) {
            val adapter = it.adapter as RecyclerAdapter
            adapter.headers = headers
            adapter.models = models
            adapter.footers = footers
        }
    }
}

@Composable
@SuppressLint("ModifierParameter")
fun Grid(
    headers: List<Any> = arrayListOf(),
    models: List<Any> = arrayListOf(),
    footers: List<Any> = arrayListOf(),
    spanCount: Int = 1,
    @RecyclerView.Orientation orientation: Int = RecyclerView.VERTICAL,
    modifier: Modifier = Modifier,
    init: RecyclerView.() -> Unit = {},
    block: RecyclerAdapter.() -> Unit = {}
) {
    RecyclerView(
        modifier = modifier
    ) {
        if (it.adapter == null) {
            init.invoke(it)
            it.grid(spanCount, orientation).setup {
                block.invoke(this)
            }
        }
        val adapter = it.adapter as RecyclerAdapter
        adapter.headers = headers
        adapter.models = models
        adapter.footers = footers
    }
}

@Composable
@SuppressLint("ModifierParameter")
fun Staggered(
    headers: List<Any> = arrayListOf(),
    models: List<Any> = arrayListOf(),
    footers: List<Any> = arrayListOf(),
    spanCount: Int = 1,
    @RecyclerView.Orientation orientation: Int = RecyclerView.VERTICAL,
    modifier: Modifier = Modifier,
    init: RecyclerView.() -> Unit = {},
    block: RecyclerAdapter.() -> Unit = {}
) {
    RecyclerView(
        modifier = modifier
    ) {
        if (it.adapter == null) {
            init.invoke(it)
            it.staggered(spanCount, orientation).setup {
                block.invoke(this)
            }
        }
        val adapter = it.adapter as RecyclerAdapter
        adapter.headers = headers
        adapter.models = models
        adapter.footers = footers
    }
}

@Composable
internal fun RecyclerView(
    modifier: Modifier = Modifier,
    update: (RecyclerView) -> Unit = {}
) {
    AndroidView(factory = { context -> RecyclerView(context) }, modifier = modifier) {
        update.invoke(it)
    }
}